package com.example.toolbar.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.ab.fragment.AbFragment;
import com.ab.http.AbHttpListener;
import com.ab.http.AbRequestParams;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.pullview.AbPullToRefreshView.OnFooterLoadListener;
import com.ab.view.pullview.AbPullToRefreshView.OnHeaderRefreshListener;
import com.ab.view.sliding.AbSlidingPlayView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.toolbar.R;
import com.example.toolbar.adapter.ArticleListAdapter;
import com.example.toolbar.global.MyApplication;
import com.example.toolbar.module.Article;
import com.example.toolbar.net.HttpRequestWrap;
import com.example.toolbar.net.NetworkWeb;
import com.example.toolbar.net.OnResponseHandler;
import com.example.toolbar.net.RequestHandler;
import com.example.toolbar.net.RequestStatus;
import com.example.toolbar.utils.imgUtils;
import com.example.toolbar.widget.FloatingActionButton;

public class fragmentPass extends AbFragment {

	private Activity mActivity = null;
	private List<Article> mList = null;
	private AbPullToRefreshView mAbPullToRefreshView = null;
	private ListView mListView = null;
	private int currentPage = 1;
	private ArticleListAdapter myListViewAdapter = null;
	private int total = 50;
	private int pageSize = 5;
	private String url = null;
	private String type = null;
	private AbSlidingPlayView mSlidingPlayView;
	LayoutInflater minflater;
	private FloatingActionButton floatingActionButton;
	private String status = null;
	private AbRequestParams params;
	private HttpRequestWrap httpRequest;
	private Context context;
	private MyApplication application;
	/*
	 * public fragmentItem() { super(); }
	 * 
	 * public fragmentItem(AbRequestParams params, String url) { this.params =
	 * params; this.url = url; }
	 */
	@Override
	public View onCreateContentView(LayoutInflater inflater,
			ViewGroup container, Bundle savedInstanceState) {
		mActivity = this.getActivity();
		application=(MyApplication) mActivity.getApplication();
		httpRequest =application.getHttpRequest();
		minflater = mActivity.getLayoutInflater();
		View view = inflater.inflate(R.layout.pull_to_refresh_list, null);
		floatingActionButton = (FloatingActionButton) view
				.findViewById(R.id.button_floating_action);
		// 获取ListView对象
		mAbPullToRefreshView = (AbPullToRefreshView) view
				.findViewById(R.id.mPullRefreshView);

		mListView = (ListView) view.findViewById(R.id.mListView);
		floatingActionButton.attachToListView(mListView);
		OnClickListener listener = new FloatLisener();
		floatingActionButton.setOnClickListener(listener);
		// 设置监听器
		mAbPullToRefreshView
				.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {

					@Override
					public void onHeaderRefresh(AbPullToRefreshView view) {
						refreshTask();
					}
				});
		mAbPullToRefreshView
				.setOnFooterLoadListener(new OnFooterLoadListener() {

					@Override
					public void onFooterLoad(AbPullToRefreshView view) {
						loadMoreTask();

					}
				});

		// 设置进度条的样式
		mAbPullToRefreshView.getHeaderView().setHeaderProgressBarDrawable(
				this.getResources().getDrawable(R.drawable.progress_loading2));
		mAbPullToRefreshView.getFooterView().setFooterProgressBarDrawable(
				this.getResources().getDrawable(R.drawable.progress_loading2));

		// ListView数据
		mList = new ArrayList<Article>();

		// 使用自定义的Adapter
		myListViewAdapter = new ArticleListAdapter(mActivity, mList);
		mSlidingPlayView = new AbSlidingPlayView(mActivity);
		mListView.setAdapter(myListViewAdapter);
		// item被点击事件
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
			}
		});

		// 加载数据必须
		this.setAbFragmentOnLoadListener(new AbFragmentOnLoadListener() {

			@Override
			public void onLoad() {
				// 第一次下载数据
				refreshTask();
			}

		});

		return view;
	}

	@Override
	public void setResource() {
		// 设置加载的资源
		this.setLoadDrawable(R.drawable.ic_load);
		this.setLoadMessage("正在查询,请稍候");

		this.setRefreshDrawable(R.drawable.ic_load);
		this.setRefreshMessage("请求出错，请重试");
	}

	/**
	 * 下载数据
	 */
	public void refreshTask() {
		currentPage = 1;
		// 绑定参数
		if (httpRequest!=null) {
			
		
		httpRequest.setMethod(HttpRequestWrap.GET);
		httpRequest.setCallBack(new RequestHandler(mActivity,
				new OnResponseHandler() {

					@Override
					public void onResponse(String result, RequestStatus status) {
						// TODO Auto-generated method stub
						System.out.println(result);
						ArrayList<Article> newList = parseData(result);
						mList.clear();
						if (newList != null && newList.size() > 0) {
							mList.addAll((List<Article>) newList);
							myListViewAdapter.notifyDataSetChanged();
							newList.clear();
						}
						mAbPullToRefreshView.onHeaderRefreshFinish();
						showContentView();

					}
				}));
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("page", String.valueOf(currentPage));
		params.put("rows", String.valueOf(pageSize));
		params.put("status", "PROCESSED");
		httpRequest
				.send("http://tr.zzapi.gson.cn/api/user/facts?page=1&rows=10&status=PROCESSED");
		// 下载网络数据
		}
	}

	public void loadMoreTask() {
		currentPage++;
		httpRequest.setMethod(HttpRequestWrap.GET);
		httpRequest.setCallBack(new RequestHandler(mActivity,
				new OnResponseHandler() {

					@Override
					public void onResponse(String result, RequestStatus status) {
						// TODO Auto-generated method stub
						if (status == RequestStatus.SUCCESS) {
							ArrayList<Article> newList = parseData(result);
							if (newList != null && newList.size() > 0) {
								mList.addAll((List<Article>) newList);
								myListViewAdapter.notifyDataSetChanged();
								newList.clear();
							}
							mAbPullToRefreshView.onFooterLoadFinish();

						}
					}
				}));
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("page", String.valueOf(currentPage));
		params.put("rows", String.valueOf(pageSize));
		params.put("status", "PROCESSED");
		httpRequest
				.send("http://tr.zzapi.gson.cn/api/user/facts?page=1&rows=10&status=PROCESSED");
	}

	private ArrayList<Article> parseData(String content) {
		JSONObject object = JSON.parseObject(content);
		JSONArray data = object.getJSONArray("data");
		ArrayList<Article> articles = new ArrayList<Article>();
		if (data != null) {
			for (int i = 0; i < data.size(); i++) {
				JSONObject curResult = data.getJSONObject(i);
				String tilte = curResult.getString("title");
				String time = curResult.getString("dateline");
				String ims = curResult.getString("images");
				String[] urls = new String[] {};
				String source = "";
				if (ims != null) {
					urls = imgUtils.getImageUrl(ims);
					source = curResult.getString("source");
				} else {
					source = "";
				}
				String commentNum = curResult.getString("commentNum");
				String id = curResult.getString("id");
				String facts = curResult.getString("fact");
				String views = curResult.getString("views");
				String good = curResult.getString("good");
				String bad = curResult.getString("bad");
				articles.add(new Article(id, tilte, urls, time, commentNum,
						facts, source, views, good, bad));
			}
		}
		return articles;
	}

	class FloatLisener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v.getId() == R.id.button_floating_action) {
				Log.d("---------", "啊啊啊啊啊");
			}
		}

	}
}
